import { SubsystemConfig } from '../interface/types/subsystem'
import { isNotEmpty } from './validate'

const subsystemConfigList: SubsystemConfig[] = []
const subsystemConfigStorer = new Map<any, SubsystemConfig>()

/**
 * 初始化 subsystemConfigStorer
 * @param subsystemConfigs 子系统配置集
 */
const initSubsystemConfigStorer = (subsystemConfigs: SubsystemConfig[]) => {
  if (isNotEmpty(subsystemConfigs)) {
    subsystemConfigs.forEach(subsystemConfig => {
      if (isNotEmpty(subsystemConfig)) {
        const id = subsystemConfig.id
        const children = subsystemConfig.children || []
        subsystemConfigStorer.set(id, subsystemConfig)
        initSubsystemConfigStorer(children)
      }
    })
  }
}

/**
 * 添加子系统配置集
 * @param subsystemConfig 子系统配置集
 */
export const addSubsystemConfigs = (...subsystemConfigs: SubsystemConfig[]) => {
  if (isNotEmpty(subsystemConfigs)) {
    initSubsystemConfigStorer(subsystemConfigs)
    subsystemConfigList.push(...subsystemConfigs)
  }
}

/**
 * 获取子系统配置集
 * @return 子系统配置集
 */
export const getSubsystemConfigs = () => {
  return subsystemConfigList
}

/**
 * 获取子系统配置
 * @param id 子系统配置 id
 * @return 子系统配置
 */
export const getSubsystemConfig = (id: string) => {
  return subsystemConfigStorer.get(id)
}
